//
//  PBEThreadManager.cpp
//  pork-belly-engine
//
//  Created by Park Han Young on 11. 11. 14..
//  Copyright (c) 2011 __MyCompanyName__. All rights reserved.
//

#include <Foundation/Foundation.h>
#include "PBEThreadManager.h"
#include "PBEThreadWrapper.h"
#include <pthread.h>

using namespace PBEngine;

namespace PBEngine
{
	class ThreadInfo
	{
	public:
		ThreadInfo(void *(*_start_routine)(void *), void* _arg)
		:start_routine(_start_routine)
		,arg(_arg)
		{}
		
		void *(*start_routine)(void *);
		void *arg;
	};
}

void* ThreadProc(void* arg);

int ThreadManager::createThread(void *(*start_routine)(void *), void *arg)
{
	pthread_t thread;
	ThreadInfo* info = new ThreadInfo(start_routine, arg);
	pthread_create(&thread, NULL, ThreadProc, info);
	
	return (int)thread;
}

void ThreadManager::runRoutineOnMainThread(void *(*routine)(void *), void* arg)
{
	ThreadWrapper* wrapper = [[ThreadWrapper alloc] initWithRoutine:routine Arg:arg];
	
	if([NSThread isMainThread])
		[wrapper performSelector:@selector(run:) withObject:nil];
	else
		[wrapper performSelectorOnMainThread:@selector(run:) withObject:nil waitUntilDone:NO];
}

void ThreadManager::sleep(unsigned int sec)
{
	sleep(sec);
}

void* ThreadProc(void* arg)
{
	NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
	
	ThreadInfo* info = (ThreadInfo*)arg;
	info->start_routine(info->arg);
	delete info;
	
	[pool release];
	return NULL;
}


